#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <iostream>

int main()
{
    if (mkfifo("mypipe", 0666) == -1)
    {
        perror("mkfile");
        exit(1);
    }
    std::cout << "创建命名管道mypipe成功" << std::endl;

    int fd = open("mypipe", O_RDONLY);
    std::cout << "读端创建成功" << std::endl;
    char buff[1024] = {0};
    while (true)
    {
        buff[0] = '\0';
        int n = read(fd, buff, 1023);
        if (n > 0)
        {
            buff[n] = '\0';
            std::cout << buff << std::endl;
        }
        if (n == 0)
        {
            std::cout << "写端已关闭,me too." << std::endl;
            break;
        }
    }
    close(fd);
    // 进程程序替换为 rm命令，删除创建的命名管道mypipe
    execl("/usr/bin/rm", "rm", "mypipe", NULL);
    return 0;
}
